package com.sskj.mqtt.many;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.jetbrains.annotations.NotNull;

import java.lang.reflect.Method;

/**
 * @Author: Like
 * @Date: 2025/3/3 15:40
 * @Description: MQTT回调函数
 */
@Slf4j
public class MqttClientCallback implements MqttCallback {

    /**
     * 系统的mqtt客户端id
     */
    private String mqttClientId;

    public MqttClientCallback(String mqttClientId) {
        this.mqttClientId = mqttClientId;
    }

    /**
     * MQTT 断开连接会执行此方法
     */
    @Override
    public void connectionLost(Throwable throwable) {
        log.info("断开了MQTT连接 ：{}", throwable.getMessage());
        log.error(throwable.getMessage(), throwable);
    }

    /**
     * publish发布成功后会执行到这里
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        log.info("发布消息成功");
    }

    /**
     * 新增静态注册方法供扫描器调用
     *
     * @param bean       对象
     * @param method
     * @param annotation
     */
    public static void registerAnnotatedMethod(Object bean, Method method, @NotNull MqttListener annotation) {
        String clientId = annotation.clientId();
        String topicFilter = annotation.topic();

        // 传递原始过滤表达式
        MqttClientMap.registerHandler(clientId, topicFilter,
                new HandlerWrapper(bean, method, topicFilter));
    }

    /**
     * 订阅后得到的消息会执行到这里
     *
     * @param topic   name of the topic on the message was published to
     * @param message the actual message.
     */
    @Override
    public void messageArrived(String topic, MqttMessage message) {
        HandlerWrapper handler = MqttClientMap.getHandler(this.mqttClientId, topic);
        if (handler != null) {
            try {
                handler.invoke(this.mqttClientId, topic, message.getPayload());
            } catch (Exception e) {
                log.error("消息处理失败 clientId={} topic={}", mqttClientId, topic, e);
            }
        }
    }
}

